package com.shiro.filter;


import com.entity.Account;
import com.servcice.AccountService;
import com.utils.ContextUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class CustomFormAuthenticationFilter extends FormAuthenticationFilter {
@Autowired
	@Lazy
AccountService accountService;
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		// 在这里进行验证码的校验
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpSession session = httpServletRequest.getSession();
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
 
//		// 取出验证码
//		String validateCode = (String) session.getAttribute("validateCode");
//		// 取出页面的验证码
//		// 输入的验证和session中的验证进行对比
//		String randomcode = httpServletRequest.getParameter("randomcode");
//		if (randomcode != null && validateCode != null && !randomcode.equals(validateCode)) {
//			// 如果校验失败，将验证码错误失败信息，通过shiroLoginFailure设置到request中
//			httpServletRequest.setAttribute("shiroLoginFailure", "randomCodeError");
//			// 拒绝访问，不再校验账号和密码
//			return true;
//		}
		
		
		//解决通过remeberMe 登录 session 无效问题

		accountService = (AccountService) ContextUtils.getSpringMVCContext().getBean("studentService");
		Subject subject = getSubject(request, response);
		Session shiroSession = subject.getSession();
		//不是认证通过 同时
		if(!subject.isAuthenticated()&&subject.isRemembered()&&session.getAttribute("user")==null){
			Object principal = subject.getPrincipal();
			if(principal != null){
				String accountname = principal.toString(); 
				Account account = accountService.getAccountByAccountName(accountname);
				shiroSession.setAttribute("user", account);
			}
		}
		
		
		
		
		return super.onAccessDenied(request, response);
	}
}
